<template>
  <div class="page-container">
    <PhotoSphereViewer style="width: 100vw; height: 100vh" ref="viewerComponent" :imgList="photoList"
      @selectMarker="handleSelectMarker" @viewerClick="handleViewerClick" @markerUpdated="handleMarkerUpdated"
      :hasGallery="true" :hasAnimate="true" :initialYaw="0" :initialPitch="0" :initialZoom="50" />

    <div class="editor-controls">
      <h2>全景编辑器</h2>
      <hr>

      <div class="control-group">
        <h3>切换场景</h3>
        <button v-for="(photo, index) in photoList" :key="photo.id" @click="viewerComponent?.updateIndex(index)">
          {{ photo.name || `场景 ${index + 1}` }}
        </button>
      </div>

      ---

      <div class="control-group">
        <h3>标记管理</h3>
        <p>选择标记类型并点击全景图添加：</p>
        <select v-model="selectedMarkerType" class="select-full-width">
          <option value="">请选择标记类型</option>
          <option value="image">图片标记</option>
          <option value="html">HTML 标记</option>
        </select>
        <button @click="toggleAddMarkerMode" :disabled="!selectedMarkerType">
          {{ isAddMarkerMode ? '退出添加标记' : `添加 ${selectedMarkerType === 'image' ? '图片' : 'HTML'} 标记` }}
        </button>

        <div v-if="selectedMarker && selectedMarker.position" class="marker-editor-panel">
          <h4>编辑标记: {{ selectedMarker.id }}</h4>
          <div v-if="selectedMarker.tooltip && typeof selectedMarker.tooltip === 'object'">
            <label>工具提示内容:</label>
            <input type="text" v-model="selectedMarker.tooltip.content" />
          </div>
          <div v-if="selectedMarker.image">
            <label>标记图片 URL:</label>
            <input type="text" v-model="selectedMarker.image" />
          </div>
          <div v-if="selectedMarker.html">
            <label>HTML 内容:</label>
            <textarea v-model="selectedMarker.html" rows="5"></textarea>
          </div>
          <div v-if="selectedMarker.size">
            <label>宽度:</label>
            <input type="number" v-model="selectedMarker.size.width" />
          </div>
          <div v-if="selectedMarker.size">
            <label>高度:</label>
            <input type="number" v-model="selectedMarker.size.height" />
          </div>
          <div>
            <label>位置 (Yaw):</label>
            <input type="number" v-model="selectedMarker.position.yaw" step="0.001" @input="saveMarkerChanges" />
          </div>
          <div>
            <label>位置 (Pitch):</label>
            <input type="number" v-model="selectedMarker.position.pitch" step="0.001" @input="saveMarkerChanges" />
          </div>
          <button @click="saveMarkerChanges">保存标记更改</button>
          <button @click="deleteMarker" class="delete-btn">删除标记</button>
        </div>
        <p v-else>请选择一个标记类型，点击“添加新标记”在全景图上创建；或者点击全景图上的现有标记进行编辑。</p>
      </div>

      ---

      <div class="control-group">
        <h3>配置保存</h3>
        <button @click="saveConfiguration">保存当前配置</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import PhotoSphereViewer from '@/components/PhotoSphereViewer.vue';
import { photos as initialPhotos } from './photos';
import type { Marker, PhotoItem } from './photos';
import { ref, watch } from 'vue';

const viewerComponent = ref<InstanceType<typeof PhotoSphereViewer> | null>(null);
const photoList = ref<PhotoItem[]>(initialPhotos);

const selectedMarker = ref<Marker | null>(null);
const isAddMarkerMode = ref(false);
const selectedMarkerType = ref<'image' | 'html' | ''>(''); // 标记类型选择

// 辅助函数：获取当前活跃场景的 PhotoItem
const getCurrentActivePhoto = () => {
  const currentIndex = viewerComponent.value?.getCurrentPhotoIndex();
  if (currentIndex !== undefined && photoList.value[currentIndex]) {
    return photoList.value[currentIndex];
  }
  return null;
};

function parseAngle(angle: any) {
  // 如果输入已经是数字，直接返回
  if (typeof angle === 'number') {
    return angle;
  }

  // 确保输入是字符串
  if (typeof angle !== 'string') {
    throw new Error('Invalid angle format');
  }

  // 移除所有空格，并转换为小写
  const str = angle.trim().toLowerCase();

  // 匹配角度单位
  if (str.endsWith('deg') || str.endsWith('°')) {
    // 提取数字并转换为弧度
    const value = parseFloat(str);
    return (value * Math.PI) / 180;
  }

  // 匹配弧度单位
  if (str.endsWith('rad') || str.endsWith('rads')) {
    // 提取数字并返回
    const value = parseFloat(str);
    return value;
  }

  // 匹配百分比单位
  if (str.endsWith('%')) {
    // 提取数字并转换为弧度（假设 100% 对应 360 度）
    const value = parseFloat(str);
    return (value / 100) * 2 * Math.PI;
  }

  // 如果没有单位，默认假定是弧度
  const value = parseFloat(str);
  if (!isNaN(value)) {
    return value;
  }

  // 无法解析
  throw new Error(`Cannot parse angle "${angle}"`);
}

// 处理选中标记事件 (当点击 viewer 上的 marker 时触发)
const handleSelectMarker = (markerp: any) => {

  const marker = markerp.config || markerp;
  console.log('页面中选中了标记:', marker);

  // 修正：构建一个完整的对象，确保所有编辑面板的参数都有初始值
  selectedMarker.value = {
    id: marker.id,
    position: {
      yaw: marker.position ? parseAngle(marker.position.yaw) : 0,
      pitch: marker.position ? parseAngle(marker.position.pitch) : 0,
    },
    image: marker.image || '',
    html: marker.html || '',
    size: marker.size ? { ...marker.size } : { width: 0, height: 0 },
    width: marker.width || 0,
    height: marker.height || 0,
    tooltip: typeof marker.tooltip === 'string'
      ? { content: marker.tooltip }
      : (marker.tooltip && typeof marker.tooltip === 'object'
        ? { ...marker.tooltip }
        : { content: '' }),
    draggable: marker.draggable || false,
  } as Marker;

  console.log('选中的标记已更新:', selectedMarker.value);
};

// 处理全景图点击事件 (用于添加新标记)
const handleViewerClick = (data: { yaw: number; pitch: number; rightclick: boolean }) => {
  console.log('页面中点击了查看器:', data);
  if (isAddMarkerMode.value && viewerComponent.value && selectedMarkerType.value) {
    let newMarkerConfig: Marker;
    const currentPhoto = getCurrentActivePhoto();

    if (!currentPhoto) {
      console.error('无法获取当前场景，无法添加标记。');
      return;
    }

    // 构建新标记配置，基于所选类型
    if (selectedMarkerType.value === 'image') {
      newMarkerConfig = {
        id: '',
        image: '/images/local.png',
        size: { width: 32, height: 32 },
        tooltip: { content: '新图片标记' },
        draggable: true,
        position: { yaw: data.yaw, pitch: data.pitch },
      };
    } else {
      newMarkerConfig = {
        id: '',
        html: `<div style="background: rgba(0,0,0,0.7); color:white; padding: 10px; border-radius: 5px;">新 HTML 标记内容</div>`,
        width: 150,
        height: 80,
        tooltip: { content: '新 HTML 标记' },
        draggable: true,
        position: { yaw: data.yaw, pitch: data.pitch },
      };
    }

    viewerComponent.value.addMarkerDirectly(newMarkerConfig);

    isAddMarkerMode.value = false;
    console.log('标记已添加！已退出添加标记模式。');
  }
};

// 处理标记更新事件 (当 marker 被拖动或新 marker 被 PhotoSphereViewer 组件添加时触发)
const handleMarkerUpdated = (updatedMarkerData: { id: string; position: { yaw: number; pitch: number }; fullMarker?: Marker }) => {
  const currentPhoto = getCurrentActivePhoto();
  if (currentPhoto && currentPhoto.markers) {
    const markerIndex = currentPhoto.markers.findIndex((m: Marker) => m.id === updatedMarkerData.id);

    if (markerIndex !== -1) {
      Object.assign(currentPhoto.markers[markerIndex], {
        position: updatedMarkerData.position,
        ...(updatedMarkerData.fullMarker ? {
          image: updatedMarkerData.fullMarker.image,
          html: updatedMarkerData.fullMarker.html,
          tooltip: updatedMarkerData.fullMarker.tooltip,
          size: updatedMarkerData.fullMarker.size,
          width: updatedMarkerData.fullMarker.width,
          height: updatedMarkerData.fullMarker.height,
        } : {})
      });
      if (selectedMarker.value && selectedMarker.value.id === updatedMarkerData.id) {
        Object.assign(selectedMarker.value, updatedMarkerData.fullMarker);
        selectedMarker.value.position = updatedMarkerData.position;
      }
      console.log(`标记 ${updatedMarkerData.id} 的新位置和属性已更新到数据模型。`);

    } else if (updatedMarkerData.fullMarker) {
      const newMarkerToAdd: Marker = {
        ...updatedMarkerData.fullMarker,
        position: updatedMarkerData.position,
        id: updatedMarkerData.id,
      };
      currentPhoto.markers.push(newMarkerToAdd);
      console.log(`新标记 ${updatedMarkerData.id} 已添加到数据模型。`);
      handleSelectMarker(newMarkerToAdd);
    }
  }
};


// 切换添加标记模式
const toggleAddMarkerMode = () => {
  if (!selectedMarkerType.value) {
    console.warn('请先选择一个标记类型！');
    return;
  }
  isAddMarkerMode.value = !isAddMarkerMode.value;
  if (isAddMarkerMode.value) {
    console.log(`已进入添加 ${selectedMarkerType.value === 'image' ? '图片' : 'HTML'} 标记模式。请点击全景图任意位置添加新标记。`);
  } else {
    console.log('已退出添加标记模式。');
  }
};

// 保存标记更改
const saveMarkerChanges = () => {
  if (selectedMarker.value && viewerComponent.value) {
    const currentPhoto = getCurrentActivePhoto();
    if (!currentPhoto) return;

    const markerIndex = currentPhoto.markers.findIndex((m: Marker) => m.id === selectedMarker.value!.id);

    if (markerIndex !== -1) {
      const updatePayload: Partial<Marker> = {
        image: selectedMarker.value.image,
        html: selectedMarker.value.html,
        tooltip: selectedMarker.value.tooltip,
        size: selectedMarker.value.size,
        position: selectedMarker.value.position,
        draggable: selectedMarker.value.draggable,
        width: selectedMarker.value.width,
        height: selectedMarker.value.height,
      };

      Object.assign(currentPhoto.markers[markerIndex], updatePayload);
      viewerComponent.value.updateMarker(selectedMarker.value.id, updatePayload);
      selectedMarker.value = null;
      console.log('标记更改已保存！');
    } else {
      console.warn('未找到要保存的标记。');
    }
  }
};

// 删除标记
const deleteMarker = () => {
  if (selectedMarker.value && viewerComponent.value) {
    const confirmDelete = confirm(`确定要删除标记 ${selectedMarker.value.id} 吗？`);
    if (!confirmDelete) return;

    viewerComponent.value.removeMarker(selectedMarker.value.id);

    const currentPhoto = getCurrentActivePhoto();
    if (currentPhoto && currentPhoto.markers) {
      currentPhoto.markers = currentPhoto.markers.filter((m: Marker) => m.id !== selectedMarker.value!.id);
      console.log('标记已删除！');
    } else {
      console.error('删除失败：无法找到当前场景。');
    }
    selectedMarker.value = null;
  }
};

// 保存当前配置到控制台 (模拟保存到后端或本地存储)
const saveConfiguration = () => {
  const currentConfig = JSON.stringify(photoList.value, null, 2);
  console.log('保存当前配置:', currentConfig);
  console.log('当前配置已保存到浏览器控制台！您可以复制粘贴它。');
};

watch(selectedMarker, (newVal) => {
  if (newVal) {
    console.log("Selected Marker updated in editor:", newVal);
  }
}, { deep: true });
</script>

<style lang="scss" scoped>
/* (样式保持不变) */
.page-container {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #222;
}

.editor-controls {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
  z-index: 1000;
  max-width: 300px;
  max-height: 90vh;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 15px;

  h2,
  h3,
  h4 {
    margin-top: 0;
    margin-bottom: 10px;
    color: #eee;
  }

  hr {
    border: none;
    border-top: 1px solid #444;
    margin: 15px 0;
  }

  .control-group {
    display: flex;
    flex-direction: column;
    gap: 8px;

    button {
      background-color: #007bff;
      color: white;
      border: none;
      padding: 8px 12px;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      transition: background-color 0.2s ease;

      &:hover {
        background-color: #0056b3;
      }

      &.delete-btn {
        background-color: #dc3545;

        &:hover {
          background-color: #c82333;
        }
      }

      &:disabled {
        background-color: #6c757d;
        cursor: not-allowed;
      }
    }

    select,
    textarea {
      width: calc(100% - 12px);
      padding: 6px;
      border: 1px solid #555;
      background-color: #333;
      color: white;
      border-radius: 3px;
    }

    .select-full-width {
      width: 100%;
    }
  }

  .marker-editor-panel {
    background-color: rgba(255, 255, 255, 0.1);
    padding: 10px;
    border-radius: 5px;
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    gap: 10px;

    label {
      font-size: 13px;
      margin-bottom: 3px;
      display: block;
    }

    input[type="text"],
    input[type="number"] {
      width: calc(100% - 12px);
      padding: 6px;
      border: 1px solid #555;
      background-color: #333;
      color: white;
      border-radius: 3px;
    }
  }
}
</style>